import 'package:flutter/material.dart';
import '../models/note.dart';
import '../services/database_service.dart';
import '../utils/loading_dialog.dart';
import 'note_edit_screen.dart';

class NoteListScreen extends StatefulWidget {
  const NoteListScreen({super.key});

  @override
  State<NoteListScreen> createState() => _NoteListScreenState();
}

class _NoteListScreenState extends State<NoteListScreen> {
  List<Note> notes = [];
  final DatabaseService _databaseService = DatabaseService();
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _loadNotes();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  Future<bool> _onWillPop() async {
  if (await _databaseService.shouldSyncDatabase()) {
    final context = this.context;
    if (!context.mounted) return true;

    LoadingDialog.show(context);
    await DatabaseService().syncDatabase();
    if (!context.mounted) return true;

    LoadingDialog.hide(context);
  }
  return true;
}


  Future<void> _loadNotes() async {
    final loadedNotes = await _databaseService.getAllNotes();
    setState(() {
      notes = loadedNotes;
    });
  }

  Future<void> _searchNotes(String query) async {
    if (query.isEmpty) {
      await _loadNotes();
    } else {
      final searchResults = await _databaseService.searchNotes(query);
      setState(() {
        notes = searchResults;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(title: const Text('我的便笺')),
        body: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                controller: _searchController,
                decoration: InputDecoration(
                  hintText: '搜索便笺...',
                  prefixIcon: const Icon(Icons.search),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                  suffixIcon: IconButton(
                    icon: const Icon(Icons.clear),
                    onPressed: () {
                      _searchController.clear();
                      _loadNotes();
                    },
                  ),
                ),
                onChanged: _searchNotes,
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: notes.length,
                itemBuilder: (context, index) {
                  final note = notes[index];
                  return Dismissible(
                    key: Key(note.id),
                    background: Container(
                      color: Colors.red,
                      alignment: Alignment.centerRight,
                      padding: const EdgeInsets.only(right: 16),
                      child: const Icon(Icons.delete, color: Colors.white),
                    ),
                    direction: DismissDirection.endToStart,
                    confirmDismiss: (direction) async {
                      return await showDialog<bool>(
                        context: context,
                        builder: (BuildContext context) {
                          return AlertDialog(
                            title: const Text('确认删除'),
                            content: const Text('确定要删除这条便笺吗？'),
                            actions: [
                              TextButton(
                                onPressed: () =>
                                    Navigator.of(context).pop(false),
                                child: const Text('取消'),
                              ),
                              TextButton(
                                onPressed: () =>
                                    Navigator.of(context).pop(true),
                                child: const Text('删除'),
                              ),
                            ],
                          );
                        },
                      );
                    },
                    onDismissed: (direction) async {
                      await _databaseService.deleteNote(note.id);
                      if (mounted) {
                        setState(() {
                          notes.remove(note);
                        });
                      }
                    },
                    child: ListTile(
                      title: Text(note.title),
                      subtitle: Text(
                        note.content,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      trailing: Text(
                        '修改于: ${note.modifiedAt.toString().substring(0, 16)}',
                        style: const TextStyle(fontSize: 12),
                      ),
                      onTap: () async {
                        final updatedNote = await Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => NoteEditScreen(note: note),
                          ),
                        );
                        if (updatedNote != null) {
                          await _databaseService.updateNote(updatedNote);
                          if (mounted) {
                            setState(() {
                              notes[index] = updatedNote;
                            });
                          }
                        }
                      },
                    ),
                  );
                },
              ),
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () async {
            final newNote = Note.create(
              id: DateTime.now().toString(),
              title: '',
              content: '',
            );
            final createdNote = await Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => NoteEditScreen(note: newNote),
              ),
            );
            if (createdNote != null) {
              await _databaseService.saveNote(createdNote);
              setState(() {
                notes.add(createdNote);
              });
            }
          },
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}
